package com.example.smartwaterapi.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Date;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Value("${jwt.header}")
    private String tokenHeader;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    @Lazy // 添加@Lazy注解以解决循环依赖
    private UserDetailsService userDetailsService; // 修改为使用接口而非实现类
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                   HttpServletResponse response, 
                                   FilterChain filterChain) throws ServletException, IOException {
        
        // 获取请求头中的Authorization
        String authHeader = request.getHeader(tokenHeader);
        
        // 判断是否以tokenHead开头
        if (StringUtils.hasText(authHeader) && authHeader.startsWith(jwtTokenUtil.getTokenHead() + " ")) {
            // 截取JWT令牌
            String authToken = authHeader.substring((jwtTokenUtil.getTokenHead() + " ").length());
            
            // 从token中获取用户名
            String username = null;
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
                log.debug("从JWT令牌中提取用户名: {}", username);
            } catch (Exception e) {
                log.error("JWT令牌解析失败: {}", e.getMessage());
            }
            
            // 验证令牌
            if (StringUtils.hasText(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                try {
                    // 加载用户
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    
                    // 验证令牌有效性
                    if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        
                        // 设置认证信息
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        log.debug("用户 [{}] 认证成功, 设置Security上下文", username);
                        
                        // 将用户ID添加到请求属性中，供后续控制器使用
                        if (userDetails instanceof SecurityUser) {
                            SecurityUser securityUser = (SecurityUser) userDetails;
                            Long userId = securityUser.getUserId();
                            if (userId != null) {
                                // 将用户ID设置为请求属性
                                request.setAttribute("userId", userId);
                                // 也可以通过自定义请求头传递（如果需要的话）
                                // 但这里使用请求属性更安全
                                log.debug("设置用户ID到请求属性: {}", userId);
                            }
                        }
                        
                        // 检查是否需要刷新活跃时间
                        if (jwtTokenUtil.shouldRefreshActiveTime(authToken)) {
                            try {
                                String refreshedToken = jwtTokenUtil.refreshTokenActiveTime(authToken);
                                // 在响应头中返回刷新后的Token
                                response.setHeader("X-Refreshed-Token", jwtTokenUtil.getTokenHead() + " " + refreshedToken);
                                log.debug("用户 [{}] Token活跃时间已刷新", username);
                            } catch (Exception e) {
                                log.warn("刷新用户 [{}] Token活跃时间失败: {}", username, e.getMessage());
                            }
                        }
                    } else {
                        log.warn("JWT令牌验证失败: {}", authToken);
                        
                        // 打印令牌的详细信息，帮助调试
                        try {
                            String tokenUsername = jwtTokenUtil.getUsernameFromToken(authToken);
                            Date expiration = jwtTokenUtil.getExpirationDateFromToken(authToken);
                            log.debug("令牌详情 - 用户名: {}, 过期时间: {}, 当前时间: {}", 
                                    tokenUsername, expiration, new Date());
                        } catch (Exception e) {
                            log.error("无法解析令牌详情: {}", e.getMessage());
                        }
                    }
                } catch (Exception e) {
                    log.error("无法设置用户认证: {}", e.getMessage(), e);
                }
            }
        } else {
            log.debug("未找到JWT令牌或格式不正确");
        }
        
        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }
} 